//BrowserAction
(function () {
	function _sendMessage(id, msg, fn) {
		chrome.tabs.sendMessage(id, msg, fn);
	}

	function sendMessage(fn) {
		var bingId = -1;
		chrome.tabs.query({}, function (tabs) {
			for (var i = 0, j = tabs.length; i < j; i++) {
				var tab = tabs[i];
				if (tab.url.indexOf("https://cn.bing.com") >= 0 && tab.url.indexOf("https://cn.bing.com/search?") < 0) {
					bingId = tab.id;
					break;
				} else if (tab.url.indexOf("https://www.bing.com") >= 0 && tab.url.indexOf("https://www.bing.com/search?") < 0) {
					bingId = tab.id;
					break;
				}
			}
			if (bingId == -1) {
				if (!confirm("没有打开Bing,是否现在打开？")) return;
				chrome.tabs.create({
					"url": "https://cn.bing.com"
				}, function (_tab) {
					bingId = _tab.id;
					_sendMessage(bingId, "getImageUrl", fn);
				});
			} else {
				_sendMessage(bingId, "getImageUrl", fn);
				return;
			}
		});
	}

	chrome.browserAction.onClicked.addListener(function (tab) {
		sendMessage(function (resp) {
			//url("http://......")
			var url = resp;
			if (url) {
				if (/"(.*?)"/g.test(url)) {
					var url = RegExp.$1;
					chrome.tabs.create({
						"url": url
					});
				}
			}
		});
	});
})();